import { checkMusic, getMusicUrl } from "@/api/song";
import type { SongLevel, TrackItem } from "@/types/song";

const onCreateNotification = (musicNotification: any): Promise<boolean> => {
  return new Promise((resolve, reject) => {
    musicNotification?.createNotification(() => {
      // this.musicNotification?.switchNotification(true);
      // isCreateNotification = true;
      resolve(true);
    });
  });
};

export const audioStore = defineStore("audioStore", {
  state: () => ({
    loading: <boolean>false,
    bgAudioManager: <UniApp.BackgroundAudioManager>{},
    songLevel: <SongLevel>"standard",
    songDetail: <TrackItem>{},
    musicNotification: <any>{},
    songList: <TrackItem[]>[],
    activeIndex: <number>0,
    isPlaying: <boolean>false,
    isCreateNotification: <boolean>false,
    // #ifdef APP-PLUS || APP-PLUS-NVUE || APP-NVUE
    globalEvent: (plus as any).globalEvent,
    // #endif
  }),
  getters: {},
  actions: {
    onInitAudio() {
      this.bgAudioManager = uni.getBackgroundAudioManager();
      this.musicNotification = uni.requireNativePlugin("XZH-musicNotification");
      try {
        if (!this.isCreateNotification) {
          this.musicNotification.init({});
          // 播放暂停
          this.globalEvent.addEventListener("musicNotificationPause", () => {
            //初始化回调
            if (this.isPlaying) {
              this.bgAudioManager.pause();
            } else {
              this.bgAudioManager.play();
            }
            this.isPlaying = !this.isPlaying;
            this.musicNotification.playOrPause(this.isPlaying);
            this.musicNotification.setPosition(
              this.bgAudioManager.currentTime * 1000
            );
          });
          // 上一首
          this.globalEvent?.addEventListener(
            "musicNotificationPrevious",
            this.onPrevMusic
          );
          // 下一首
          this.globalEvent?.addEventListener(
            "musicNotificationNext",
            this.onNextMusic
          );
        }

        this.bgAudioManager; // 自然播放结束
        this.bgAudioManager.onEnded(this.onNextMusic);
      } catch (error) {
        console.log(error);
      }
    },
    async onGetUrl(songList: TrackItem[], index: number) {
      this.activeIndex = index;
      this.songList = songList;
      if (songList[index].id === this.songDetail.id) return;
      this.loading = true;
      this.songDetail = songList[index];
      try {
        const {
          code: checkCode,
          success,
          message,
        } = await checkMusic(this.songDetail.id);
        if (checkCode === 200) {
          if (!success) {
            uni.showToast({
              title: message,
              icon: "none",
              duration: 1000,
            });
            return;
          } else {
            const { data } = await getMusicUrl({
              id: this.songDetail.id,
              level: this.songLevel,
            });
            if (!this.isCreateNotification) {
              this.isCreateNotification = await onCreateNotification(
                this.musicNotification
              );
            }

            this.musicNotification.update({
              //歌曲名字
              songName: this.songDetail.name,
              //专辑名字
              artistsName: this.songDetail.al.name,
              //搜藏
              favour: true,
              //专辑图片
              picUrl: this.songDetail.al.picUrl,
              // 时长
              duration: data[0].time,
            });
            this.musicNotification.setPosition(0);
            this.musicNotification.playOrPause(true);
            this.bgAudioManager.src = data[0].url;
            this.bgAudioManager.title = this.songDetail.name;
            this.bgAudioManager.coverImgUrl = this.songDetail.al.picUrl;
            this.bgAudioManager.singer = this.songDetail.ar
              .map((item) => item.name)
              .join("、");
            this.bgAudioManager.duration = data[0].time;
            this.bgAudioManager.play();
            this.isPlaying = true;
          }
        }
      } finally {
        setTimeout(() => (this.loading = false), 300);
      }
    },
    onDestroyAudio() {
      (plus as any).globalEvent.removeEventListener("musicNotificationPause");
      (plus as any).globalEvent.removeEventListener("musicNotificationPause");
      (plus as any).globalEvent.removeEventListener("musicNotificationPause");
    },
    // 下一首
    onNextMusic() {
      let index: number = this.activeIndex + 1;
      if (index > this.songList.length - 1) {
        index = 0;
      }
      this.activeIndex = index;
      this.onGetUrl(this.songList, index);
    },
    // 上一首
    onPrevMusic() {
      let index: number = this.activeIndex - 1;
      if (index < 0) {
        index = this.songList.length - 1;
      }
      this.activeIndex = index;
      this.onGetUrl(this.songList, index);
    },
    onPlay() {
      if (this.bgAudioManager.paused) {
        this.bgAudioManager.play();
        this.isPlaying = true;
      } else {
        this.bgAudioManager.pause();
        this.isPlaying = false;
      }
    },
  },
});
